package com.albon.alarm;

import java.util.Calendar;
import java.util.HashMap;



import com.albon.baseball.Baseball;
import com.albon.baseball.DatabaseHelper;
import com.albon.sportsalarm.R;
import com.albon.util.Logg;
import com.albon.util.ToastMaster;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class BaseballSetAlarm extends Activity implements OnClickListener, StaticVariable{
	 private final String TAG = "BaseballSetAlarm";
	 
	 private Intent ringtonePickerIntent = null;
		private String uri;
		private ContentResolver resolver;
		private  Context mContext;
		public HashMap<String, String> alarmSettingsValues = new HashMap<String, String>();
			
		private String league_title;
		private String key_compare_date;
		private String key_a_team;
		private String key_b_team;
		private String real_date;
		private String real_time;
		private String key_year;
		private String key_month;
		private String stadium;
		private boolean key_enable;
		
		private int key=1;
		
		private final int INSERTMODE = 0;
		private final int UPDATEMODE = 1;
		
		private int mode = 0;
		
		private String ringtone_uri = "Off";
		private int nMax;
		private int nCurrentVolumn;
		private AudioManager audioManager;
		private int resetVolume;
		private Baseball baseball;
		
		
		private final int ALARM_RINGTONE = 0;
		private final int MUSIC_RINGTONE = 1;
		private final int REQUESTCODE_NOTIFICATION_ALARM = 3;
		private final int REQUESTCODE_ALARM_AUTO_OFF_TIME = 4;
		
		
		private  String[] auto_alarm_off_time_name_array =  {};
		private int auto_alarm_off_time_value = 0;
		
		private long set_alarm_time = 0L;
		private  int notification_time_value = 0;
		private  String[] notification_time_array_name =  {}; 
		private  String[] notification_time_array_value =  {}; 
		
		private TextView real_date_time;
		private TextView team_match;
		private TextView match_stadium;
		private LinearLayout alarm_turn_group;
		private CheckedTextView alarm_turn_checkbox;
	    private LinearLayout notification_time_group;    
	    private TextView notification_time_sub;
	    private LinearLayout alarm_tone_group;
	    private TextView alarm_tone_sub;
	    private SeekBar volume_seekbar;
	    private LinearLayout alarm_vib_group;
	    private CheckedTextView alarm_vib_checkbox;
	    private LinearLayout auto_alarm_off_time_group;
	    private TextView auto_alarm_off_time_sub;
	    private EditText league_explanation;
	    private Button save_btn;
	    private Button cancel_btn;
	       
	    
	    void init(){
	    	
	    	real_date_time = (TextView)findViewById(R.id.real_date_time);
	    	team_match = (TextView)findViewById(R.id.team_match);
	    	match_stadium = (TextView)findViewById(R.id.match_stadium);
	    	alarm_turn_group = (LinearLayout)findViewById(R.id.alarm_turn_group);
	    	alarm_turn_group.setOnClickListener(this);
	    	alarm_turn_checkbox = (CheckedTextView)findViewById(R.id.alarm_turn_checkbox);
	    	alarm_turn_checkbox.setChecked(key_enable);
	    	notification_time_group = (LinearLayout)findViewById(R.id.notification_time_group);
	    	notification_time_group.setOnClickListener(this);
	    	notification_time_sub = (TextView)findViewById(R.id.notification_time_sub);
	    	alarm_tone_group = (LinearLayout)findViewById(R.id.alarm_tone_group);
	    	alarm_tone_group.setOnClickListener(this);
	    	alarm_tone_sub = (TextView)findViewById(R.id.alarm_tone_sub);
	    	volume_seekbar = (SeekBar)findViewById(R.id.volume_seekbar);
	    	alarm_vib_group = (LinearLayout)findViewById(R.id.alarm_vib_group);
	    	alarm_vib_group.setOnClickListener(this);
	    	alarm_vib_checkbox = (CheckedTextView)findViewById(R.id.alarm_vib_checkbox);
	    	auto_alarm_off_time_group = (LinearLayout)findViewById(R.id.auto_alarm_off_time_group);
	    	auto_alarm_off_time_group.setOnClickListener(this);
	    	auto_alarm_off_time_sub = (TextView)findViewById(R.id.auto_alarm_off_time_sub);
	    	league_explanation = (EditText)findViewById(R.id.league_explanation);
	    	save_btn = (Button)findViewById(R.id.save_btn);
	    	save_btn.setOnClickListener(this);
	    	cancel_btn = (Button)findViewById(R.id.cancel_btn);
	    	cancel_btn.setOnClickListener(this);
	    	auto_alarm_off_time_name_array = getResources().getStringArray(R.array.auto_alarm_off_time_name_value);
	    	notification_time_array_name = getResources().getStringArray(R.array.notification_time_array_name);
	    	notification_time_array_value = getResources().getStringArray(R.array.notification_time_array_value);
	    	real_date_time.setText(real_date+" "+real_time);
	    	team_match.setText(key_a_team +" VS "+key_b_team);
	    	match_stadium.setText(stadium);
	    	
	    }
	    
	    @Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			final Window win = getWindow();
	        win.requestFeature(Window.FEATURE_NO_TITLE);
	        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
	                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON );
			setContentView(R.layout.sports_set_alarm);
			resolver = getContentResolver(); 
			mContext = this;
			league_title = getIntent().getStringExtra("league_title");
	        key_compare_date = getIntent().getStringExtra("compare_date");
	        key_a_team = getIntent().getStringExtra("a_team");
	        key_b_team = getIntent().getStringExtra("b_team");
	        real_date = getIntent().getStringExtra("real_date");
	        real_time = getIntent().getStringExtra("real_time");
	        key_year = getIntent().getStringExtra("year");
	        key_month = getIntent().getStringExtra("month");
	        stadium = getIntent().getStringExtra("stadium");
	        key_enable = getIntent().getBooleanExtra("enable",false);
	        init();
	        call_alarm_values();
	        if(mode==UPDATEMODE){
	        	upate_mode();
	        }else{
	        	match_stadium.setText(stadium);
	        	notification_time_sub.setText(notification_time_array_name[notification_time_value]);
	        	auto_alarm_off_time_sub.setText(auto_alarm_off_time_name_array[auto_alarm_off_time_value]);
	        }
	        sound_seek();        
		}
	    
	    private void upate_mode() {
			// TODO Auto-generated method stub
			
			alarm_turn_checkbox.setChecked(Boolean.valueOf(baseball.getEnable()));
			ringtone_uri = baseball.getAlarm_ringtone();
			rington_uri(ringtone_uri);
			notification_time_value = Integer.parseInt(baseball.getNotification());
			notification_time_sub.setText(notification_time_array_name[notification_time_value]);
			alarm_vib_checkbox.setChecked(Boolean.valueOf(baseball.getAlarm_vibrate()));
			auto_alarm_off_time_value = Integer.parseInt(baseball.getAlarm_auto_off_time());
			auto_alarm_off_time_sub.setText(auto_alarm_off_time_name_array[auto_alarm_off_time_value]);
			league_explanation.setText(baseball.getExplanation());
		}
		//링톤읽어와 저장
	    void rington_uri(String ringtone){
	    	Logg.d(TAG, "ringtone : "+ringtone);
	    	Cursor ring = null;
	    	boolean find_ringtone = false;
	    	
	    	try {
				ring = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS, "", null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
				if(ring != null && ring.moveToFirst()){
					alarm_tone_sub.setText(getText(R.string.silent_alarm_summary).toString());
					do{
						Uri uri1 = ContentUris.withAppendedId(Uri.parse(ring.getString(2)), ring.getLong(0));
						Logg.e(TAG, "uri1 = " + uri1.toString());
						Logg.d(TAG, "ring = " + ringtone);
						
						if(uri1.toString().equalsIgnoreCase(ringtone)){
							alarm_tone_sub.setText(ring.getString(1));
							Logg.d(TAG,"ring.getString(1) : "+ring.getString(1));
							find_ringtone = true;
							break;
						}
					}while(ring.moveToNext());
					
				}
					if(!find_ringtone){
						Logg.d(TAG,"find_ringtone : "+find_ringtone);
						Cursor cur = null;
						try {
							cur = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, EXTERNAL_COLUMNS, "", null, "_id");
							if(cur == null){
								//내부 링톤과 외부링톤 모두 못찾을시 무음으로 변환
								Logg.d(TAG, "cur == null");		
								ringtone_uri = "Off";
								alarm_tone_sub.setText(getText(R.string.silent_alarm_summary).toString());
							}else{
								if ( cur.moveToFirst() ) {
									do {	
										Logg.d(TAG, "cur != null");		
										Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
										if ( uri1.toString().equalsIgnoreCase(ringtone) ) {
											Logg.e(TAG, "cur.getString(1) : "+cur.getString(1));
											alarm_tone_sub.setText(cur.getString(1));
											break;
										}
									}while(cur.moveToNext());
								}
							}
						}catch (Exception e) {
							// TODO: handle exception
							Logg.e(TAG, "e //: "+e);
						}finally{
							if(cur!=null){
								cur.close();
							}
						}
					}
			} catch (Exception e) {
				// TODO: handle exception
			}finally{
				if(ring!=null){
					ring.close();
				}
			}
	    }
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.save_btn:
				
				/**
				 * 현재시간을 캘린더 setTimeInMillis 에 넣어준다.
				 * 설정한 시,분,초을 캘린더에 set 해준다.
				 * 캘린더에서 getTimeInMillis 을 가져온다.
				 */
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				long cur_time = calendar.getTimeInMillis();
				
				
				/*Logg.d(TAG, "key_compare_date : "+key_compare_date);		
				Logg.d(TAG, "day : "+key_compare_date.substring(6));
				Logg.d(TAG, "real_time 1: "+real_time.substring(0, 2));
				Logg.d(TAG, "real_time 2: "+real_time.substring(3));*/
				
				String day = key_compare_date.substring(6);
				String hour = real_time.substring(0, 2);
				String minute = real_time.substring(3);
				calendar.set(Calendar.YEAR, Integer.parseInt(key_year));
				calendar.set(Calendar.MONTH, Integer.parseInt(key_month)-1);
				calendar.set(Calendar.DATE, Integer.parseInt(day));
				calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
				calendar.set(Calendar.MINUTE, Integer.parseInt(minute));
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				
				if(notification_time_value==0){
					set_alarm_time = calendar.getTimeInMillis();
				}else{
					set_alarm_time = calendar.getTimeInMillis()-Long.valueOf(notification_time_array_value[notification_time_value]);
				}
				if(cur_time>set_alarm_time){ ////현재 시작보다 설정한시간이 지난시간이면 알람 안울림
					Toast.makeText(BaseballSetAlarm.this, R.string.past_time, Toast.LENGTH_LONG).show();	
				}else{
					if(mode==INSERTMODE){
						 save_value();
						}else{
						 update_value(key);
						}
					
					alarmSettingsValues.put("tone", "Off");
					audioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);// music 볼륨을 기존 music 볼륨으로 초기화시킨다.
					finish();
				}
				break;
			case R.id.cancel_btn:
				alarmSettingsValues.put("tone", "Off");
				 audioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
				finish();
				break;
			case R.id.alarm_turn_group:
				
				if(alarm_turn_checkbox.isChecked()){
					alarm_turn_checkbox.setChecked(false);				
				}else{
					alarm_turn_checkbox.setChecked(true);				
				}
				break;
			case R.id.notification_time_group:
				Intent send_noti_alarm = new Intent(BaseballSetAlarm.this, NotiAlarmTimeList.class);
				send_noti_alarm.putExtra("send_noti_alarm", notification_time_sub.getText().toString());
				startActivityForResult(send_noti_alarm, REQUESTCODE_NOTIFICATION_ALARM);
				break;
			case R.id.alarm_tone_group:
				ringtonePopup();
				break;
			case R.id.alarm_vib_group:
				if(alarm_vib_checkbox.isChecked()){
					alarm_vib_checkbox.setChecked(false);				
				}else{
					alarm_vib_checkbox.setChecked(true);				
				}
				break;
			case R.id.auto_alarm_off_time_group:
				Intent alarm_off_time = new Intent(this,  AlarmOffTimeList.class);
				 alarm_off_time.putExtra("alarm_off_time", auto_alarm_off_time_value);
				 startActivityForResult(alarm_off_time, REQUESTCODE_ALARM_AUTO_OFF_TIME);
				break;
			
			}
		}
		
	    //알람 DB 저장
		private void save_value(){
			SQLiteDatabase databse = null;
			
			if(databse == null){
				databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
			}
			
			String enabled = String.valueOf(alarm_turn_checkbox.isChecked());		
			String alarm_ringtone = alarmSettingsValues.get("tone");
			String alarm_volume = String.valueOf(nCurrentVolumn);
			String alarm_vibrate = String.valueOf(alarm_vib_checkbox.isChecked());
			String notification = String.valueOf(notification_time_value);
			String alarm_auto_off_time = String.valueOf(auto_alarm_off_time_value);
			String explanation = league_explanation.getText().toString();
			
			ContentValues values = new ContentValues();
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE, league_title);
			values.put(DatabaseHelper.DATABASE_COLUMN_ENABLED, enabled);
			values.put(DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE, key_compare_date);
			values.put(DatabaseHelper.DATABASE_COLUMN_REAL_DATE, real_date);
			values.put(DatabaseHelper.DATABASE_COLUMN_REAL_TIME, real_time);
			values.put(DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR, key_year);
			values.put(DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH, key_month);
			values.put(DatabaseHelper.DATABASE_COLUMN_A_TEAM, key_a_team);
			values.put(DatabaseHelper.DATABASE_COLUMN_B_TEAM, key_b_team);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE, alarm_ringtone);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME, alarm_volume);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE, alarm_vibrate);
			values.put(DatabaseHelper.DATABASE_COLUMN_NOTIFICATION, notification);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME, alarm_auto_off_time);
			values.put(DatabaseHelper.DATABASE_COLUMN_EXPLANATION, explanation);
			
			long aid = databse.insert(DatabaseHelper.DATABASE_TABLE_NAME, null, values);
			if(aid == -1){
				Logg.e(TAG,"db insert - error occurred");
			}else{
				//save한 리스트 key값 가져오기 start
				Cursor cursor = null;
				try {
					cursor = databse.rawQuery("SELECT "
							+ DatabaseHelper.DATABASE_COLUMN_ID + " " + " FROM "
							+ DatabaseHelper.DATABASE_TABLE_NAME , null);

					int max = 1;				
					if (cursor != null && cursor.moveToFirst()) {					
						try{
							do {
								max = cursor.getInt(0);
								
							} while (cursor.moveToNext());
							if(alarm_turn_checkbox.isChecked()){
								setAlarm(max); // 알람메니저에 등록
							}
						}catch (Exception e2) {
							// TODO: handle exception
							Logg.e(TAG, "e2 "+e2);
						}
					}
				} finally {
					if (cursor != null)
						cursor.close();				
				}
				//save한 리스트 key값 가져오기 end
			}
			if(databse != null){
				databse.close();
			}
		}
		
		//알람 DB 업데이트
		private void update_value(int key) {
			Logg.d(TAG, "key : "+key);
			cancelAlarm(key);
			SQLiteDatabase databse = null;
			if(databse == null){
				databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
			}
			
			String _id = String.valueOf(key);
			
			String enabled = String.valueOf(alarm_turn_checkbox.isChecked());		
			String alarm_ringtone = this.ringtone_uri;
			String alarm_volume = String.valueOf(nCurrentVolumn);
			String alarm_vibrate = String.valueOf(alarm_vib_checkbox.isChecked());
			String notification = String.valueOf(notification_time_value);
			String alarm_auto_off_time = String.valueOf(auto_alarm_off_time_value);
			String explanation = league_explanation.getText().toString();
			
			ContentValues values = new ContentValues();
			values.put(DatabaseHelper.DATABASE_COLUMN_ENABLED, enabled);
			values.put(DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE, key_compare_date);
			values.put(DatabaseHelper.DATABASE_COLUMN_A_TEAM, key_a_team);
			values.put(DatabaseHelper.DATABASE_COLUMN_B_TEAM, key_b_team);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE, alarm_ringtone);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME, alarm_volume);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE, alarm_vibrate);
			values.put(DatabaseHelper.DATABASE_COLUMN_NOTIFICATION, notification);
			values.put(DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME, alarm_auto_off_time);
			values.put(DatabaseHelper.DATABASE_COLUMN_EXPLANATION, explanation);
			
			
			long uid = databse.update(DatabaseHelper.DATABASE_TABLE_NAME, values, "_id=?", new String [] {_id});
			Logg.d(TAG, "uid : "+uid);
			if(uid == -1){			
				Logg.e(getLocalClassName(),"db update - error occurred");
			}else{
				if(alarm_turn_checkbox.isChecked()){
					setAlarm(key);
				}
			}
			if(databse != null){
				databse.close();
				databse = null;
			}
			
		}
		
		//알람매니저에 알람등록!
		private void setAlarm(int key) {
			// TODO Auto-generated method stub
			Intent intent_send = new Intent(ALARM_BASEBALL_ALERT_ACTION);
	    	intent_send.putExtra("key", key);
	    	PendingIntent sender = PendingIntent.getBroadcast(mContext, key, intent_send, 0);
			AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, set_alarm_time, sender);
			popAlarmSetToast(this, set_alarm_time);
		}
		
		//알람매니저 알람 취소
		private void cancelAlarm(int key){
			
			AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
			Intent intent = new Intent(ALARM_BASEBALL_ALERT_ACTION);
			intent.putExtra("key", key);
			PendingIntent sender = PendingIntent.getBroadcast(mContext, key, intent, 0);
			
			if(am != null)
			{
				am.cancel(sender);
				am = null;
			}
		}
		
			
			
		void sound_seek(){
	    	audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
	    	resetVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);// music 현재 볼륨을 가져와서 finish 할때 원복시켜준다.
	    	
			nMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);	//music 최고 볼륨을 가져온다.
			Logg.d(TAG, "nMax : "+nMax);
			if(mode==INSERTMODE){
				audioManager.setStreamVolume(AudioManager.STREAM_ALARM, nMax, 0);
				nCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
	       }else{
	    	   if(baseball.getAlarm_volume() == null || baseball.getAlarm_volume().equals("")){
	    		   audioManager.setStreamVolume(AudioManager.STREAM_ALARM, nMax, 0);
	    	   }else{
	    	       audioManager.setStreamVolume(AudioManager.STREAM_ALARM, Integer.parseInt(baseball.getAlarm_volume()), 0);
	    	   }
	    	       nCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
	       }
			Logg.d(TAG, "nCurrentVolumn : "+nCurrentVolumn);
			volume_seekbar.setMax(nMax);
			volume_seekbar.setProgress(nCurrentVolumn);

			volume_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

				
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
				   stop();	
				}

				
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					play();
				}

			
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// TODO Auto-generated method stub
					audioManager.setStreamVolume(AudioManager.STREAM_ALARM, progress, 0);				
					Logg.d(TAG, "progress : "+progress);
					nCurrentVolumn = progress;
					
				}
			});
	    }
		 private MediaPlayer mp;
		    public  void play( ) { 
			    String music = "";
				mp= new MediaPlayer();
				try {
					final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
					if(mode==INSERTMODE){
						music = alarmSettingsValues.get("tone");
		            }else{
		            	music = ringtone_uri;
		            }
					mp.setDataSource(this, Uri.parse(music));// mp3파일 경로
					mp.setAudioStreamType(AudioManager.STREAM_ALARM);
					mp.prepare(); // 준비
					mp.setVolume(audioManager.getStreamVolume(AudioManager.STREAM_RING), audioManager.getStreamVolume(AudioManager.STREAM_RING));
					mp.setLooping(true); // 반복재생 true
					mp.start(); // 시작		
					
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
			}
			public  void stop() { 
			
				if (mp != null) {
					mp.stop(); // 중지
					mp.release(); // 자원 반환
					mp = null;
				}
			}
			
			AlertDialog.Builder ring_pop = null;
			private void ringtonePopup(){
			    	
					if (this.ring_pop != null) return ;
					
					final int ALARM_RINGTONE = 0;
					final int MUSIC_RINGTONE = 1;
					
			    	CharSequence[] ringtone_array = new CharSequence[2];
			    	ringtone_array[ALARM_RINGTONE] = this.getResources().getString(R.string.alarm_ringtone); 
			    	ringtone_array[MUSIC_RINGTONE] = this.getResources().getString(R.string.music_ringtone); 
			    	
			    	ring_pop = new AlertDialog.Builder(this);  	
			    	ring_pop
					//.setTitle(R.string.alarm_sound)
					.setOnCancelListener(new OnCancelListener() { 
						public void onCancel(DialogInterface dialog) { 
								if(ring_pop != null) {						
									ring_pop = null;
								}
						}
					}).setItems(ringtone_array, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int typeInd3x) {
							
							switch (typeInd3x) {
							case ALARM_RINGTONE :
								alarm_ringtone();
								break;
								
							case MUSIC_RINGTONE :
								music_ringtone();
								break;
							} 
							
							
							ring_pop = null;
						} 
					}).show();
					
			    }
			
			//알람 벨소리 다이얼로그 창 불러오기
		    private void alarm_ringtone() {
		    	
		        Uri findTone = null;
		        if(ringtonePickerIntent == null) { 
		            ringtonePickerIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
		            String tone = "";
		            if(mode==INSERTMODE){
		            	 tone	= alarmSettingsValues.get("tone");
		            }else{
		            	 tone = ringtone_uri;
		            }
		            
		            Logg.d(TAG, "tone : " + tone);
		            if (tone != null){
		                findTone = Uri.parse(tone);
		            }
		        
		            if (tone == null || tone.equalsIgnoreCase("Off") || "".equals(tone.trim())) {
		                findTone = null;
		            }
		            ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, findTone);
		            ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
		            ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
		            ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
		            ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, BaseballSetAlarm.this.getResources().getString(R.string.ringtone));
		            startActivityForResult(ringtonePickerIntent, ALARM_RINGTONE);
		        }
		    }
		    
		    //뮤직 벨소리 다이얼로그 창 불러오기   
		    private void music_ringtone(){
		    	 
		    	 Intent intent = new Intent(this, MusicRingtone.class);   
		    	 
		             String tone = "";
		             if(mode==INSERTMODE){
		             	 tone	= alarmSettingsValues.get("tone");
		             }else{
		             	 tone = ringtone_uri;
		             }
		             
		             Logg.d(TAG, "tone : " + tone);          
		             intent.putExtra("music_tone", tone);            
		             startActivityForResult(intent, MUSIC_RINGTONE);
		    }

			@Override
			protected void onActivityResult(int requestCode, int resultCode,
					Intent data) {
				// TODO Auto-generated method stub
				super.onActivityResult(requestCode, resultCode, data);
				switch (requestCode) {
				case REQUESTCODE_NOTIFICATION_ALARM:
					if(resultCode == RESULT_OK){	
						notification_time_value=data.getIntExtra("sendData", 0);
						notification_time_sub.setText(notification_time_array_name[notification_time_value]);	
						
					}
					break;
				case REQUESTCODE_ALARM_AUTO_OFF_TIME://타이머 종료시간
					if(resultCode == RESULT_OK){				
						auto_alarm_off_time_value = data.getIntExtra("alarm_off_time", 0);		
						auto_alarm_off_time_sub.setText(auto_alarm_off_time_name_array[auto_alarm_off_time_value]);
					}
					break;	
				case MUSIC_RINGTONE :
					String musicToneText = "";
					if(data != null){
						Uri music_uri = null;
						String music_alarm = data.getStringExtra("music_alarm");
						Logg.d(TAG, "music_alarm : "+music_alarm);
						if(music_alarm != null && !music_alarm.equals("")){
				    		 music_uri = Uri.parse(music_alarm); 				
						}
						if(music_uri == null){
							musicToneText = BaseballSetAlarm.this.getText(R.string.silent_alarm_summary).toString(); 
			                alarmSettingsValues.put("tone", "Off");
			                ringtone_uri = "Off";
						}else if(music_uri != null){
							Logg.d(TAG,"music_uri.toString() : " + music_uri.toString());
							musicToneText = music_uri.toString();
							Cursor cur = null;
			            	try {
								cur = resolver.query(music_uri, new String[] { "title" }, null, null, null);
								if (cur != null && cur.moveToFirst()) {
								    do {  
								    	Logg.d(TAG, "cur.getString(0) : " + cur.getString(0) );
								    	musicToneText = cur.getString(0);     
								    } while (cur.moveToNext());
								}
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								if ( cur != null )
									cur.close();
							}
							alarmSettingsValues.put("tone", music_uri.toString() );
							ringtone_uri = music_uri.toString();
						}
					}
					if (resultCode==RESULT_OK) {
		        		Logg.d(TAG, " toneText : "+musicToneText); 
		        		alarm_tone_sub.setText(  musicToneText  );								
		        	} 
		        	
					break;
				case ALARM_RINGTONE :
					 String toneText = "";
			            
			    		if (data != null) {
			                Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			                
			                if (uri == null) {

				                toneText = BaseballSetAlarm.this.getText(R.string.silent_alarm_summary).toString(); 
				                alarmSettingsValues.put("tone", "Off");
				                ringtone_uri = "Off";
			                } else if (uri != null) {
			                	Logg.d(TAG,"uri.toString() : " + uri.toString());
			                	toneText = uri.toString();
			                	
			                	Cursor cur = null;
			                	try {
									cur = resolver.query(uri, new String[] { "title" }, null, null, null);
									if (cur != null && cur.moveToFirst()) {
									    do {  
									    	Logg.d(TAG, "cur.getString(0) : " + cur.getString(0) );
									    	toneText = cur.getString(0);     
									    } while (cur.moveToNext());
									}
								} catch (Exception e) {
									e.printStackTrace();
								} finally {
									if ( cur != null )
										cur.close();
								}
								alarmSettingsValues.put("tone", uri.toString() );
								ringtone_uri = uri.toString();
			                }
			    		}
			                     
			        	if (resultCode==RESULT_OK) {
			        		Logg.d(TAG, " toneText : "+toneText); 
			        		alarm_tone_sub.setText(  toneText  );								
			        	} 
			        	if(ringtonePickerIntent != null) {
			        		ringtonePickerIntent = null;
			        	}
					break;

				
				}
			} 
		    
			private static void popAlarmSetToast(Context context, long timeInMillis) {
		        String toastText = formatToast(context, timeInMillis);
		        Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
		        ToastMaster.setToast(toast);
		        toast.show();
		      
		    }
		    
			 /**
		     * Toast 설정
		     * 
		     */
		    static String formatToast(Context context, long timeInMillis) {
		        long delta = timeInMillis - System.currentTimeMillis();
		        long hours = delta / (1000 * 60 * 60);
		        long minutes = delta / (1000 * 60) % 60;
		        long days = hours / 24;
		        hours = hours % 24;

		        String daySeq = (days == 0) ? "" :
		                (days == 1) ? context.getString(R.string.day) :
		                context.getString(R.string.days, Long.toString(days));

		        String minSeq = (minutes == 0) ? "" :
		                (minutes == 1) ? context.getString(R.string.minute1) :
		                context.getString(R.string.minutes, Long.toString(minutes));

		        String hourSeq = (hours == 0) ? "" :
		                (hours == 1) ? context.getString(R.string.hour1) :
		                context.getString(R.string.hours, Long.toString(hours));

		        boolean dispDays = days > 0;
		        boolean dispHour = hours > 0;
		        boolean dispMinute = minutes > 0;

		        int index = (dispDays ? 1 : 0) |
		                    (dispHour ? 2 : 0) |
		                    (dispMinute ? 4 : 0);

		        String[] formats = context.getResources().getStringArray(R.array.alarm_set);
		        return String.format(formats[index], daySeq, hourSeq, minSeq);
		    }
		    
		  //알람 값을 불러온다.
		    void call_alarm_values(){
		    	SQLiteDatabase databse = null;		
				if(databse == null){
					databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
				}
				String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + " = '" +key_compare_date+"' and "+ DatabaseHelper.DATABASE_COLUMN_A_TEAM +" = '"+key_a_team+"' and "+DatabaseHelper.DATABASE_COLUMN_B_TEAM+" = "+"'"+key_b_team+"'";		
				
				Cursor cursor = null;

				try {
					cursor = databse.rawQuery("SELECT "
							+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
							+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
							+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
							+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
							+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
							+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
							+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
							+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
							+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
							+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
							+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
							+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
							+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
							+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
							+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
							+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
							+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
					if (cursor != null && cursor.moveToFirst()) {
						do {
							baseball = new Baseball(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
							mode = 1; 
							key = cursor.getInt(0);
						} while (cursor.moveToNext());
					}		
							
										
				} finally {
					if (cursor != null)
						cursor.close();
					if(databse != null){
						databse.close();
					}
				}
		    }
}
